package com.cnwidsom.plugins.persistence;

import java.beans.IntrospectionException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import org.bson.Document;

import com.cnwidsom.monitor.MonitorItem;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBPersistence implements Persistence {
	private Map<String, String> params;
	private MongoClient client;
	private String dbName;

	public String getName() {
		return "mongodb";
	}

	public void writeData(MonitorItem mi) {
		MongoDatabase database = client.getDatabase(dbName);
		MongoCollection<Document> pathData_collection = database.getCollection("path_data");

		try {
			pathData_collection.insertOne(mi.toDocument());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (IntrospectionException e) {
			e.printStackTrace();
		}
	}

	public void setParameters(Map<String, String> params) {
		this.params = params;
		if (params != null && params.get("database") != null) {
			dbName = params.get("database");
			String user = params.get("user");
			String pass = params.get("pass");
			String server = params.get("server");
			String port = params.get("port");
			String connectUrl = "";
			if (user == null || user.trim().equalsIgnoreCase(""))
				connectUrl = "mongodb://" + server + ":" + port;
			else
				connectUrl = "mongodb://" + user + ":" + pass + "@" + server + ":" + port + "/?authSource=" + dbName;
			client = new MongoClient(new MongoClientURI(connectUrl, MongoClientOptions.builder().cursorFinalizerEnabled(false)));
		}
	}
}
